from django.shortcuts import render
import redis, requests, json, random
from django.http import HttpResponse, HttpResponseBadRequest
from tuijiantask.relative import xiangshidu,tuijian,get_support
# Create your views here.

localhost = '47.103.7.159'
port = '6379'
POLL = redis.ConnectionPool(host=localhost,
                   port=port,
                   password='maoandyou',
                   db=2)
PACKAGLISTNAME = 'packagelist'
MODELNAME = 'model'

# list 迭代器
def list_iter(name):
    redisConn = redis.StrictRedis(connection_pool=POLL)
    list_count = redisConn.llen(name)
    for index in range(list_count):
        yield redisConn.lindex(name, index).decode('utf8')


class MyModel:
    PACKAGE = None
    SUPPORTDATA = None

    def __init__(self):
        self.PACKAGE = self.getPackage()
        self.SUPPORTDATA = get_support(self.PACKAGE)

    # 获取菜谱 list
    def getPackage(self):
        redisConn = redis.StrictRedis(connection_pool=POLL)
        packagelist = []
        # 根据 菜谱 名找到 菜品 字符串
        for package in list_iter(PACKAGLISTNAME):
            package = redisConn.get(package).decode('utf8')
            packagelist.append(package.split('_'))
        return packagelist

    def updateModel(self):
        self.savePackage()
        self.PACKAGE = self.getPackage()
        self.SUPPORTDATA = get_support(self.PACKAGE)

    # 存储 菜谱 list
    def savePackage(self,data):
        packagelist = requests.get('http://47.107.173.225:5000/api/get_package_id_list').json()
        redisConn = redis.StrictRedis(connection_pool=POLL)
        packagelistname = PACKAGLISTNAME
        packagename_pre = 'package_'
        packagename_suffix = 0
        redisConn.delete(packagelistname)
        for package in packagelist:
            packagename_suffix = packagename_suffix + 1
            packagename = packagename_pre + str(packagename_suffix)
            # 在 添加数据前删除原数据
            redisConn.rpush(packagelistname, packagename)
            # 在 添加数据前删除原数据
            redisConn.delete(packagename)
            dishstr = '_'.join(package)
            redisConn.set(packagename, dishstr)
        result = 1
        return result

mymodel = MyModel()

def index(request, op):
    data = request.GET
    print(data)
    result = eval(op)(data)
    return HttpResponse(
        result,
        content_type='application/json',
        charset='utf-8'
    )

# 推荐 菜品
def dish(data):
    id = data.get('dishid')
    result = tuijian(id, mymodel.SUPPORTDATA)
    i = random.randint(10, 60)
    if result == []:
        result = mymodel.PACKAGE[i]
    print(result)
    return json.dumps(result, ensure_ascii=False)

# 推荐 套餐
def pkg(data):
    dishid = data.get('dishid').split('_')
    package = mymodel.PACKAGE
    caipulist = xiangshidu(dishid, package)[0:5]
    result = []
    for caipu in caipulist:
        result.append(caipu[0])
    return json.dumps(result, ensure_ascii=False)

def update(data):
    mymodel.updateModel()